package com.jacky.iot.resources;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.OptionSet;
import org.eclipse.californium.core.coap.Response;
import org.eclipse.californium.core.network.Exchange;
import org.eclipse.californium.core.observe.ObserveRelation;
import org.eclipse.californium.core.observe.ObserveRelationFilter;
import org.eclipse.californium.core.server.resources.CoapExchange;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;

public class DeviceAwareObservableResource  extends CoapResource {


    // 维护设备号与观察者关系的映射表
    private final Map<String, ObserveRelation> deviceObservers = new HashMap<>();
    private String message = "当前资源状态";

    public DeviceAwareObservableResource(String name) {
        super(name);
        setObservable(true); // 启用可观察
        getAttributes().setObservable();
    }

    @Override
    public void handleGET(CoapExchange exchange) {
        exchange.respond(this.message);
    }

    @Override
    public void addObserveRelation(ObserveRelation relation) {
        super.addObserveRelation(relation);
        // 从请求中解析设备号（例如通过URI查询参数）
        Exchange exchange = relation.getExchange();
        OptionSet options = exchange.getRequest().getOptions();
        String deviceId = options.getUriQueryParameter().getArgument("deviceId");
        if (deviceId != null && !deviceId.isEmpty()) {
            deviceObservers.put(deviceId, relation);
            System.out.println("设备 " + deviceId + " 注册观察者");
        }
    }

    @Override
    public void removeObserveRelation(ObserveRelation relation) {
        super.removeObserveRelation(relation);
        // 清理已失效的观察者
        deviceObservers.values().removeIf(obs -> obs.equals(relation));
    }

    // 根据设备号触发通知
    public void notifyDevice(String deviceId, String message) {
        ObserveRelation devRelation = deviceObservers.get(deviceId);
        if (devRelation != null) {
            this.message = message;
            this.changed(relation -> relation.equals(devRelation));
            System.out.println("向设备 " + deviceId + " 发送通知");
        } else {
            System.out.println("设备 " + deviceId + " 未注册观察者");
        }
    }
}
